package com.mj.torrentsearch.activity;

import com.mj.torrentsearch.R;
import com.mj.torrentsearch.service.TorrentsearchService;
import com.mj.torrentsearch.util.NetUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

/**
 * 欢迎界面
 * @author zhaominglei
 * @date 2015-5-10
 * 
 */
public class SplashActivity extends Activity {
	@SuppressWarnings("unused")
	private static final String TAG = SplashActivity.class.getSimpleName();
	
	private static final int SPLASH_DISPLAY_LENGHT = 8*1000; //延迟8秒
	private static final int STOP_SPLASH = 1;
	private SplashActivityHandler splashActivityHandler = new SplashActivityHandler();
	private Intent intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		
		//同步数据
		if (NetUtils.isConnected(getApplicationContext())) {
			new SyncDataTask().start();
		} else {
			splashActivityHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					Intent intent = new Intent(SplashActivity.this, MainActivity.class);
					SplashActivity.this.startActivity(intent);
					SplashActivity.this.finish();
				}
			}, SPLASH_DISPLAY_LENGHT);
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	// TODO 将来可以加个进度条 后面主程序加载完后通知欢迎页面
	@SuppressLint("HandlerLeak")
	public class SplashActivityHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case STOP_SPLASH:
				intent = new Intent(SplashActivity.this, MainActivity.class);
				SplashActivity.this.startActivity(intent);
				SplashActivity.this.finish();
				break;
			
			default:
				intent = new Intent(SplashActivity.this, MainActivity.class);
				SplashActivity.this.startActivity(intent);
				SplashActivity.this.finish();
				break;
			}
			super.handleMessage(msg);
		}
	}
	
	/**
	 * 同步数据任务
	 * 
	 */
	public class SyncDataTask extends Thread {
		private TorrentsearchService torrentsearchService = new TorrentsearchService();

		@Override
		public void run() {
			//同步最新的种子
			torrentsearchService.syncLatestTorrent(getApplicationContext());

			Message msg = new Message();
			msg.what = STOP_SPLASH;
			splashActivityHandler.sendMessage(msg);
		}
	}
}
